package com.springboot.cloud.seckill.rest;

import com.springboot.cloud.common.core.entity.vo.Result;
import com.springboot.cloud.seckill.dao.SeckillRepository;
import com.springboot.cloud.seckill.entity.SeckillActivity;
import com.springboot.cloud.seckill.service.ISeckillAdminService;
import com.springboot.cloud.seckill.service.ISeckillService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.*;

import java.time.Instant;

/**
 * @author godyao
 * @date 2022/3/26
 */
@RequestMapping("/seckill")
@RestController
@Api("seckill")
@Slf4j
public class SeckillController {
    @Autowired
    private ISeckillAdminService iSeckillAdminService;

    @Autowired
    private ISeckillService iSeckillService;

    @Autowired
    private SeckillRepository seckillRepository;

    /**
     * 获取当前服务器时间
     */
    @GetMapping("/")
    public Result getServerTime() {
        return Result.success(Instant.now());
    }

    @PostMapping("/seckillActivity")
    public Result addActivity(@RequestBody SeckillActivity seckillActivity) {
        return Result.success(iSeckillAdminService.addActivity(seckillActivity));
    }

    @GetMapping("/seckillActivity/{id}")
    public Result addActivity(@PathVariable Long id) {
        return Result.success(iSeckillAdminService.queryActivityById(id).get());
    }

    @GetMapping("/seckillActivity/")
    public Result addActivity(PageRequest pageRequest) {
        return Result.success(iSeckillAdminService.queryActivity(pageRequest));
    }


    @DeleteMapping("/seckillActivity/{id}")
    public Result deleteActivity(@PathVariable Long id) {
        iSeckillAdminService.deleteActivity(id);
        return Result.success("OK");
    }

    /**
     * 秒杀
     * @param goodsId
     * @param code
     * @return
     */
    @GetMapping("/secKill/{code}/{goodsId}")
    public Result secKill(@PathVariable Long goodsId, @PathVariable String code) {
        if (!iSeckillService.checkUrlInvalid(code, goodsId)) {
            final String msg = "url code验证不通过";
            log.info(msg);
            return Result.fail(msg);
        }
        return Result.success(iSeckillService.secKill(goodsId));
    }

    @GetMapping("/secKill/updateStock")
    public void updateStockByGoodsId(Long goodsId, Integer stock) {
        seckillRepository.updateStockCount(goodsId, stock);
    }
}
